package com.example.taobaounion.ui.fragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.viewpager.widget.ViewPager
import com.example.taobaounion.R
import com.example.taobaounion.base.BaseFragment
import com.example.taobaounion.model.bean.Categories
import com.example.taobaounion.model.bean.Data
import com.example.taobaounion.presenter.impl.HomePresenterImpl
import com.example.taobaounion.view.IHomeCallBack
import com.example.taobaounion.ui.adapter.HomeViewPagerAdapter
import com.example.taobaounion.utils.PresenterManager
import com.google.android.material.tabs.TabLayout

/**
 *@author : Administrator
 *@descreption : 主Fragment界面
 */
class HomeFragment : BaseFragment(), IHomeCallBack {
    private lateinit var homePresenterImpl: HomePresenterImpl
    private lateinit var adapter: HomeViewPagerAdapter
    private var categoryList: ArrayList<Data> = ArrayList()
    private var tabLayoutHome: TabLayout? = null
    private var viewPagerHome: ViewPager? = null

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        setRootView(R.layout.home_fragment_base_view)
        return super.onCreateView(inflater, container, savedInstanceState)
    }

    override fun setPresenter() {
        homePresenterImpl = PresenterManager.getInstance().homePresenterImpl
        homePresenterImpl.registerCallBack(this)
        homePresenterImpl.getCategories()
    }
    override fun initData() {
        setViewState(State.LOADING)
    }

    override fun setRootView(rootViewID: Int) {
        super.setRootView(rootViewID)
    }

    override fun setLayoutResourcesID(): Int {
        return R.layout.fragment_home
    }


    override fun reLoadData(){
      // LogUtil.d(HomeFragment::class.java,"重新加载了")
       homePresenterImpl.getCategories()
   }

    override fun initView(container: View) {

        this.tabLayoutHome = container.findViewById(R.id.tabLayout_home)
        this.viewPagerHome = container.findViewById(R.id.viewPager_home)
        tabLayoutHome?.setupWithViewPager(viewPagerHome)
        adapter = HomeViewPagerAdapter(childFragmentManager) //这里必须要填childFragmentManager
        // 因为这里是Fragment嵌套Fragment,不是Activity嵌套fragment
        viewPagerHome?.adapter = adapter
    }

    override fun loadCategories(categories: Categories?) {
        setViewState(State.SUCCESS)
        if (categories == null) return
        categoryList.clear()
        this.categoryList.addAll(categories.data)
        adapter.setData(categoryList)
        adapter.notifyDataSetChanged()
        //viewPagerHome?.offscreenPageLimit = categoryList.size  加载的fragment个数 默认不写是2个


    }

    override fun loading() {
        setViewState(State.LOADING)
    }

    override fun error() {
        setViewState(State.ERROR)
    }

    override fun noData() {
        setViewState(State.NONE)
    }



}